//
//  WSJPopview.m
//  BaxTer
//
//  Created by wsj2015 on 16/9/1.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "WSJPopview.h"
#import "KLCPopup.h"
#import "LoginWelcomeView.h"
#import "LDProgressView.h"
#import "BTRatingView.h"
#import "CKHttpCommunicate.h"
#import "HELPDFfileCacheTool.h"

@interface WSJPopview ()

@property (nonatomic,  strong) KLCPopup *pop;

@property (nonatomic,  strong) LDProgressView *progressView;

@property (nonatomic,  strong) UILabel *titleL;

@property (nonatomic,  strong) BTCourseModel *course;

@property (nonatomic,  strong) NSString *urlStr;


@property (nonatomic, strong) NSURLSessionDownloadTask *downTask;

@property (nonatomic,  strong) UIButton *canBtn;
@end
@implementation WSJPopview

+ (instancetype)sharedWsjPopView{
    
    return [[WSJPopview alloc] init];
    
    
    
}

- (void)showLoginWelcome{
    
    
    
    //    CGFloat f = kScreenFactor;
    ;
    
    LoginWelcomeView *loginWelcomeView =[LoginWelcomeView loginWelcomeViewWithClickBlock:nil];
    
    loginWelcomeView.frame =CGRectMake(0, 0, 270, 118 );
    loginWelcomeView.backgroundColor = [UIColor whiteColor];
    
    
    KLCPopup *pop =  [KLCPopup popupWithContentView:loginWelcomeView showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeBounceOutToTop maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:NO dismissOnContentTouch:NO];
    loginWelcomeView.confirmclickBlock = ^(){
        [pop dismiss:YES];
    };
    [pop show];
    
}


- (void)showFinishiedReward{
    
    UIImageView *imageView =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"积分弹框"]];
    
    CGFloat f  = kScreenFactor;
    CGFloat w = 280 * f;
    imageView.frame = CGRectMake(0, 0,w, w/1.1 );
    KLCPopup *pop =  [KLCPopup popupWithContentView:imageView showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeBounceOutToTop maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:YES dismissOnContentTouch:NO];
    
    [pop show];
}


- (void)showTrainingcampFinishing{
    
    UIImageView *imageView =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gongxi_guoguan"]];
    [imageView sizeToFit];
    KLCPopup *pop =  [KLCPopup popupWithContentView:imageView showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeBounceOutToTop maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:YES dismissOnContentTouch:NO];
    
    [pop show];
    
}


- (void)showRatingView:(BOOL)isAbleRate withHelpScore:(CGFloat)helpScore withContentScore:(CGFloat)contentScore withDoneBlock:(void(^)(CGFloat help_score,CGFloat content_score))doneBlock{
    
    CGFloat f = kScreenFactor;
    weakSelf_define;
    BTRatingView *ratingView = [BTRatingView ratingView];
    
    ratingView.frame =CGRectMake(0, 0, 300 * f, 180);
    KLCPopup *pop =  [KLCPopup popupWithContentView:ratingView showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeBounceOutToTop maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:YES dismissOnContentTouch:NO];
    [pop show];
    __weak typeof(ratingView) weakR = ratingView;
    if (isAbleRate == YES) {
        ratingView.confirmBlock = ^(CGFloat h,CGFloat c){
            
            doneBlock(h,c);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakR removeFromSuperview];
            });
            [pop dismiss:YES];
        };
        
        
    }else{
        
        ratingView.help_score = helpScore;
        ratingView.contet_score = contentScore;
        ratingView.ableToRate = NO;
        
        ratingView.confirmBlock = ^(CGFloat h,CGFloat c){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakR removeFromSuperview];
            });
            [pop dismiss:YES];
        };
        
    }
    
}


- (void)startDownload{
    
    weakSelf_define;
    __block BOOL isFail = 0;
    self.downTask = [CKHttpCommunicate createDownloadFileWithURLString:weakSelf.urlStr downloadFileProgress:^(NSProgress *progress) {
        if (isFail == 1) {
            return ;
        }
        //       __block typeof(weakSelf) self = weakSelf;
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            self.progress = progress.fractionCompleted;
            
            //            hud.label.text = [NSString stringWithFormat:@"已下载%.f%%",progress.fractionCompleted *100];
        });
        
        //        WSJLog(@"---%f,%f",progress,progress.completedUnitCount);
        
    } setupFilePath:^NSURL *(NSURLResponse *response) {
        
        //        NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        BOOL isMP4 = NO;
        if ([weakSelf.course.courseType integerValue] == 1) {
            isMP4 = YES;
        }
        return [NSURL fileURLWithPath: [HELPDFfileCacheTool getDownloadPathWithPdfName:weakSelf.course.courseName isMp4:isMP4]];
        
    } downloadCompletionHandler:^(NSURL *filePath, NSError *error) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (error) {
                isFail = 1;
                alertMessage(error.localizedDescription);
                //                [weakSelf btnClick];
                //下载出错  移除可能的文件
                //                [HELPDFfileCacheTool removePdfFileWithPdfNames:@[weakSelf.course.courseName]];
                [self.pop dismiss:YES];
                return ;
            }
            weakSelf.titleL.text  =@"下载完成";
            weakSelf.progressView.progress = 1;
            if (weakSelf.doneBlock) {
                weakSelf.doneBlock();
            }
            [weakSelf.canBtn setTitle:@"确定" forState:UIControlStateNormal];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.pop dismiss:YES];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self clear];
                });
            });
            
            
            
            
        });
        
    }];
    
}

- (instancetype)showDownLoadWithCourse:(BTCourseModel *)course{
    
    self.course = course;
    if (course.courseUrl) {
        self.urlStr = [NSString stringWithFormat:@"%@/%@%@",[BTNetworkManager sharedMg].bathURL,kCourseDeload,course.courseUrl];
        if ([course.courseUrl rangeOfString:@"http:"].length) {
            self.urlStr = course.courseUrl;
        }
        
    }else{
        self.urlStr = @"";
    }
    
    
    UIView *view =[UIView new];
    CGFloat f = kScreenFactor;
    view.frame = CGRectMake(0, 0, 268 * f, f *130);
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    
    CGFloat w = 268 * f;
    UILabel *label = [UILabel new];
    label.frame = CGRectMake(0, 15, w, 20);
    label.font = [UIFont systemFontOfSize:17];
    label.text = @"正在下载中...";
    label.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label];
    
    self.titleL = label;
    
    LDProgressView * progressView = [[LDProgressView alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(label.frame) + 10 *f, w-40, 22)];
    progressView.color = [UIColor greenColor];
    progressView.flat = @YES;
    progressView.progress = 0.0;
    progressView.animate = @YES;
    progressView.showText = @YES;
    //    progressView.showStroke = @YES;
    progressView.progressInset = @0;
    progressView.showBackground = @YES;
    //    progressView.backgroundColor = [UIColor lightGrayColor];
    //    progressView.outerStrokeWidth = @1;
    progressView.type = LDProgressGradient;
    //    progressView.showTextAlways = @YES;
    //    progressView.textColor = [UIColor whiteColor];
    //    progressView.textAlignment =@(0);
    [view addSubview:progressView];
    self.progressView = progressView;
    
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
    //    btn.center = CGPointMake(view.center.x, );
    CGFloat btnw = 120 *f;
    btn.frame = CGRectMake((w - btnw) /2, CGRectGetMaxY(progressView.frame) + 10 * f, 120 *f, 33);
    [btn setBackgroundColor:kMainColor];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:17];
    [view addSubview:btn];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.cornerRadius = 10;
    btn.layer.masksToBounds = YES;
    self.canBtn = btn;
    self.pop =  [KLCPopup popupWithContentView:view showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeBounceOut maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:NO dismissOnContentTouch:NO];
    [self.pop show];
    [self.pop setValue:@(1) forKey:@"isShowing"];
    weakSelf_define;
    self.pop.didFinishDismissingCompletion = ^(){
        
        [weakSelf clear];
    };
    
    [self startDownload];
    
    
    
    return self;
    
}




- (void)btnClick{
    
    if (self.cancelBlock) {
        self.cancelBlock();
    }
    
    self.titleL.text  =@"取消中...";
    self.progress = 0.0;
    [self.downTask cancel];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.pop dismiss:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self clear];
        });
    });
    
    
    
}
- (void)clear{
    
    self.downTask = nil;
    //    [self.progressView removeObserver:self forKeyPath:@"progress"];
    
    for (UIView *v in self.pop.subviews) {
        [v removeFromSuperview];
    }
    
    self.pop = nil;
    
    
}


- (void)dealloc{
    
    
}
- (void)setProgress:(CGFloat)progress{
    _progress = progress;
    self.progressView.progress = progress;
}

@end
